package com.zjc.yohoshop.mvp.view.fragment;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ccmit.zxinglibrary.activity.CaptureActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zjc.lib_core.base.BaseFragment;
import com.zjc.yohoshop.R;
import com.zjc.yohoshop.bean.CouponListEntity;
import com.zjc.yohoshop.bean.UpgradeEntity;
import com.zjc.yohoshop.di.compont.DaggerHomeFragmentCompont;
import com.zjc.yohoshop.mvc.view.FragmentActivity;
import com.zjc.yohoshop.mvp.view.adapter.HomeCategoryTabAdapter;
import com.zjc.yohoshop.mvp.view.adapter.HomeGoodsAdapter;
import com.zjc.yohoshop.mvp.view.adapter.HomeRecommendAdapter;
import com.zjc.yohoshop.bean.HomeBannerEntity;
import com.zjc.yohoshop.bean.HomeGoodsEntity;
import com.zjc.yohoshop.bean.HomeRecommendEntity;
import com.zjc.yohoshop.di.modules.HomeFragmentModules;
import com.zjc.yohoshop.eventbus_bean.BaseEventBusEntity;
import com.zjc.yohoshop.eventbus_bean.OpenEventBus;
import com.zjc.yohoshop.listener.HomeBannerImageLoader;
import com.zjc.yohoshop.mvp.contract.HomeFragmentContract;
import com.zjc.yohoshop.mvp.persenter.HomeFragmentPresenter;
import com.zjc.yohoshop.network.API;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页界面
 */
public class HomeFragment extends BaseFragment<HomeFragmentPresenter> implements HomeFragmentContract.HomeFragmentIView, View.OnClickListener, BaseRefreshListener{
    private View view, bannerView, categoryView;
    private LinearLayout ll_home_search;
    private PullToRefreshLayout ptrl_home_fragment;
    private RecyclerView rv_home_fragment, rv_home_top, rv_home_tab, rv_home_recommend;
    private LinearLayout ll_home_top_bg;
    private Banner banner;
    private HomeBannerEntity bannerEntity;
    private HomeRecommendAdapter recommendAdapter;
    private HomeCategoryTabAdapter tabAdapter, topAdapter;
    private HomeGoodsAdapter goodsAdapter;

    private int bannerHeight = 0;
    private int categoryHeight = 0;
    private int totalY = 0;

    private ImageView iv_home_fragment_sliding_menu_left;
    private ImageView iv_home_navbar_qrcode;
    private ImageView iv_home_navbar_msg;

    @Override
    public View createView(LayoutInflater inflater) {
        view = inflater.inflate(R.layout.fragment_home, null);
        return view;
    }

    @Override
    public void init(View view) {
        ll_home_search = view.findViewById(R.id.ll_home_search);
        //初始化侧滑菜单按钮
        iv_home_fragment_sliding_menu_left = view.findViewById(R.id.iv_home_fragment_sliding_menu_left);
        //初始化扫描二维码按钮
        iv_home_navbar_qrcode = view.findViewById(R.id.iv_home_navbar_qrcode);
        //初始化消息按钮
        iv_home_navbar_msg = view.findViewById(R.id.iv_home_navbar_msg);
        //初始化刷新控件
        ptrl_home_fragment = view.findViewById(R.id.ptrl_home_fragment);
        //初始化fragment关联的控件
        rv_home_fragment = view.findViewById(R.id.rv_home_fragment);
        ll_home_top_bg = view.findViewById(R.id.ll_home_top_bg);
        rv_home_tab = view.findViewById(R.id.rv_home_tab);
        //初始化banner控件
        bannerView = View.inflate(getActivity(), R.layout.item_home_banner, null);
        banner = bannerView.findViewById(R.id.ban_home_head);
        //初始化category控件
        categoryView = View.inflate(getActivity(), R.layout.item_home_recommend, null);
        rv_home_top= categoryView.findViewById(R.id.rv_home_goods_category_tab);
        //初始化推荐values控件
        rv_home_recommend = categoryView.findViewById(R.id.rv_recommend_url);
        //测量banner以及category高度
        bannerView.measure(0, 0);
        categoryView.measure(0, 0);
        //获取measure高度
        bannerHeight = bannerView.getMeasuredHeight();
        categoryHeight = categoryView.getMeasuredHeight();
        //添加适配器相关
        //recommend推荐配置
        LinearLayoutManager recommend_layout = new LinearLayoutManager(getActivity());
        recommend_layout.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_home_recommend.setLayoutManager(recommend_layout);
        recommendAdapter = new HomeRecommendAdapter(R.layout.item_home_recommend_item);
        rv_home_recommend.setAdapter(recommendAdapter);
        //tabAdapter配置
        LinearLayoutManager tab_layout = new LinearLayoutManager(getActivity());
        tab_layout.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_home_top.setLayoutManager(tab_layout);
        topAdapter = new HomeCategoryTabAdapter(R.layout.item_home_goods_title);
        rv_home_top.setAdapter(topAdapter);
        //topAdapter配置
        LinearLayoutManager top_tab_layout = new LinearLayoutManager(getActivity());
        top_tab_layout.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_home_tab.setLayoutManager(top_tab_layout);
        tabAdapter = new HomeCategoryTabAdapter(R.layout.item_home_goods_title);
        rv_home_tab.setAdapter(tabAdapter);
        //推荐values配置
//        rv_home_recommend.set
        //homeAdapter配置
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
        rv_home_fragment.setLayoutManager(gridLayoutManager);
        rv_home_fragment.addOnScrollListener(new HomeRecyclerListener());
        goodsAdapter = new HomeGoodsAdapter(R.layout.item_home_goods);
        //添加头布局
        goodsAdapter.addHeaderView(bannerView, 0);
        goodsAdapter.addHeaderView(categoryView, 1);
        rv_home_fragment.setAdapter(goodsAdapter);



    }

    @Override
    public void initData() {
        p.requestAll();

        PackageManager manager = getActivity().getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getActivity().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = info.versionName;
        //下面的代码是获取版本Code
        int  versionCode = info.versionCode;

        Toast.makeText(getActivity(), "" + versionCode, Toast.LENGTH_SHORT).show();

        p.upgrade("" + versionCode);
    }

    @Override
    public void setupDagger() {
        DaggerHomeFragmentCompont.builder().homeFragmentModules(new HomeFragmentModules(this))
                .build().inject(this );
    }

    @Override
    public void bannerSuccess(HomeBannerEntity entity) {
        bannerEntity = entity;
        List<String> strings = new ArrayList<>();
        for (HomeBannerEntity.Values values : entity.values){
            strings.add(API.BaseUrl + values.recommend_url);
        }
        banner.setImages(strings);
        banner.setImageLoader(new HomeBannerImageLoader());
        banner.isAutoPlay(true);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setDelayTime(1 * 1500);
        banner.start();
    }

    @Override
    public void recommendSuccess(HomeRecommendEntity entity) {
        recommendAdapter.addData(entity.recommend);
        entity.category.get(0).isSelector = true;
        tabAdapter.addData(entity.category);
        topAdapter.addData(entity.category);

    }

    @Override
    public void goodsSuccess(HomeGoodsEntity entity) {
        if (entity.values == null){
            Toast.makeText(getActivity(), "首页 -> 商品 -> 没数据了", Toast.LENGTH_SHORT).show();
            return;
        }
        goodsAdapter.addData(entity.values);
    }
    //请忽略
    @Override
    public void couponlistSuccess(CouponListEntity entity) {}

    //软件升级接口返回
    @Override
    public void UpgradeSuccess(UpgradeEntity entity) {
        Toast.makeText(getActivity(), "" + entity.statues + "、" + entity.msg, Toast.LENGTH_SHORT).show();
        if ("1".equals(entity.statues)){
            Toast.makeText(getActivity(), entity.msg, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void initListener() {
        iv_home_fragment_sliding_menu_left.setOnClickListener(this);
        iv_home_navbar_qrcode.setOnClickListener(this);
        iv_home_navbar_msg.setOnClickListener(this);
        ptrl_home_fragment.setRefreshListener(this);
        topAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                totalY = 0;
                for (HomeRecommendEntity.Category category : topAdapter.getData()){
                    category.isSelector = false;
                }
                topAdapter.getData().get(position).isSelector = true;
                topAdapter.notifyDataSetChanged();

                for (HomeRecommendEntity.Category category : tabAdapter.getData()){
                    category.isSelector = false;
                }
                tabAdapter.getData().get(position).isSelector = true;
                tabAdapter.notifyDataSetChanged();

                goodsAdapter.getData().clear();
                goodsAdapter.notifyDataSetChanged();
                p.refresh(topAdapter.getData().get(position).category_id);

            }
        });
        tabAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                totalY = 0;
                for (HomeRecommendEntity.Category category : tabAdapter.getData()){
                    category.isSelector = false;
                }
                tabAdapter.getData().get(position).isSelector = true;
                tabAdapter.notifyDataSetChanged();

                for (HomeRecommendEntity.Category category : topAdapter.getData()){
                    category.isSelector = false;
                }
                topAdapter.getData().get(position).isSelector = true;
                topAdapter.notifyDataSetChanged();

                goodsAdapter.getData().clear();
                goodsAdapter.notifyDataSetChanged();
                p.refresh(tabAdapter.getData().get(position).category_id);
            }
        });

        ll_home_search.setOnClickListener(this);

        /**
         * 商品点击事件
         */
        goodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent goodsValues = new Intent(getActivity(), FragmentActivity.class);
                goodsValues.putExtra("type", "goods_values");
                goodsValues.putExtra("goods_id", goodsAdapter.getData().get(position).goods_id);
                getActivity().startActivity(goodsValues);
            }
        });

        /**
         * 推荐点击事件
         */
//        recommendAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Intent goodsValues = new Intent(getActivity(), FragmentActivity.class);
//                goodsValues.putExtra("type", "goods_values");
//                goodsValues.putExtra("goods_id", recommendAdapter.getData().get(position).recommend_id);
//                getActivity().startActivity(goodsValues);
//            }
//        });

        /**
         * banner轮播点击事件
         */
//        banner.setOnBannerClickListener(new OnBannerClickListener() {
//            @Override
//            public void OnBannerClick(int position) {
//                Intent goodsValues = new Intent(getActivity(), FragmentActivity.class);
//                goodsValues.putExtra("type", "goods_values");
//                goodsValues.putExtra("goods_id", bannerEntity.values.get(position - 1).recommend_id);
//                getActivity().startActivity(goodsValues);
//            }
//        });


        //滑动监听
        rv_home_fragment.addOnScrollListener(new HomeRecyclerListener());

    }

    @Override
    public void showDialog() {

    }

    @Override
    public void hideDialog() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_home_fragment_sliding_menu_left://点击图片打开侧滑才散
                EventBus.getDefault().post(new OpenEventBus(BaseEventBusEntity.OPENMENU));
                break;
            case R.id.ll_home_search:
                Toast.makeText(getActivity(), "搜索框", Toast.LENGTH_SHORT).show();
                break;
            case R.id.iv_home_navbar_qrcode:
                openCqpture();
                break;
            case R.id.iv_home_navbar_msg:
                break;
        }
    }

    //开启ZXing提供的扫码界面
    private void openCqpture() {
        Intent intent = new Intent(getActivity(), CaptureActivity.class);
        getActivity().startActivityForResult(intent,100);
    }

    //TODO 首页列表goods刷新
    @Override
    public void refresh() {
        goodsAdapter.getData().clear();
        p.requestAll();
        ptrl_home_fragment.finishRefresh();
    }

    //TODO 首页列表goods加载
    @Override
    public void loadMore() {
        p.loadMore();
        ptrl_home_fragment.finishLoadMore();
    }

    //RecyclerView滑动监听器
    private class HomeRecyclerListener extends RecyclerView.OnScrollListener{
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            totalY += dy;
            float alpah = (float)totalY / (float)bannerHeight;
            //alpha 0-1;
            if (alpah > 1){
                alpah = 1;
            }
            if (alpah <= 0){
                alpah = 0;
            }
            ll_home_top_bg.setAlpha(alpah);
            GridLayoutManager manager = (GridLayoutManager)recyclerView.getLayoutManager();
            int position = manager.findLastVisibleItemPosition();
            if (position>=5){
                rv_home_tab.setVisibility(View.VISIBLE);
            }else {
                rv_home_tab.setVisibility(View.GONE);
            }
        }
    }

}
